<template>
  <el-dialog class="print" :visible.sync="isShow" :before-close="handleCancelModal" :show-close="true" :close-on-click-modal="false" width="680px">
    <span slot="title">选择打印模板</span>
    <div v-loading="isLoad" class="container">
      <div v-if="tplList.length" class="tpl-buy">
        <div style="margin-bottom: 2px">通用模板</div>
        <div class="tpl-container">
          <div v-for="(item, index) in tplList" :key="index" class="tpl-item" @click="handleTemplate(item.tpl_id)">
            <div class="image-container">
              <el-image :src="completionImageLocal(item.cover)" fit="cover" class="avatar">
                <div slot="error" class="image-slot">没有图片</div>
              </el-image>
              <label v-if="template && template.tpl_id === item.tpl_id" class="mark">
                <i class="el-icon-check" />
              </label>
            </div>
            <div class="tpl-text">{{ item.title }}</div>
          </div>
        </div>
      </div>
    </div>
    <!-- 提交按钮 -->
    <div slot="footer" class="dialog-footer">
      <div style="display: flex;justify-content: space-between">
        <div style="position: relative;left: -2px;top: -3px">
          <el-button type="text" class="el-icon-download color-danger" @click="handleDownloadZpi">下载打印控件</el-button>
          <el-button type="text" class="el-icon-download color-danger" style="margin-right: 10px" @click="handleOpenUrl">下载标签机驱动</el-button>
          <span style="font-size: 13px">当前有 <span class="color-success">{{ printData['lists'].length }}</span> 条数据待打印</span>
        </div>
        <div>
          <el-button size="small" @click="handleCancelModal">关闭</el-button>
          <el-button size="small" @click="handlePrint('preview')">预览</el-button>
          <el-button type="primary" size="small" @click="handlePrint">打印</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { lodop, printLabel } from '@/utils/print'
import { info } from '@/api/print-tpl'
import { tplReplace } from '@/utils/template'
import { fileUrl } from '@/utils/tools'

export default {
  name: 'Print',
  props: {
    isShow: { type: Boolean, default: true },
    tplId: { type: Number, default: null },
    tplList: { type: Array, default: null },
    printData: { type: Object, default: null },
    tplMark: { type: String, default: null },
    cacheMark: { type: String, default: null }
  },
  data: function() {
    return {
      isLoad: true,
      desc: null,
      template: null
    }
  },
  mounted: function() {
    if (this.tplId) {
      this.handleTemplate(this.tplId)
    } else {
      this.$nextTick(function() {
        this.isLoad = false
      })
    }
  },
  methods: {
    handlePrint(button = null) {
      try {
        if (!this.template) {
          this.$message.warning('请选择打印模板')
          return false
        }
        if (this.template.mode === 'goods_label') {
          printLabel(this.printData, this.template, button, _ => {
            this.handleCancelModal()
          })
        } else {
          const params = this.printData ? JSON.parse(JSON.stringify(this.printData)) : []
          delete params.lists
          const LODOP = lodop()
          LODOP.PRINT_INIT('打印清单')
          // 纸张设置
          let width = 210
          // let height = 297
          let mainTop = 0
          let mainLeft = 0
          if (this.template.width) {
            width = Number(this.template.width)
          }
          // if (this.template.height) {
          //   height = Number(this.template.height)
          // }
          if (this.template.lists && this.template.lists.mainTop) {
            mainTop = Number(this.template.lists.mainTop)
          }
          if (this.template.lists && this.template.lists.mainLeft) {
            mainLeft = Number(this.template.lists.mainLeft)
          }
          LODOP.SET_PRINT_PAGESIZE(0, 0, 0, 'A4')
          if (this.template.header) {
            // 插入页眉
            LODOP.ADD_PRINT_HTM(0, 0, '207mm', '5mm', tplReplace(this.template.header, params))
            // 设置刚加入的能让，每页都显示
            LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1)
            // 设置对象在纸张范围内水平居中
            LODOP.SET_PRINT_STYLEA(0, 'Horient', 2)
          }
          if (this.template.footer) {
            // 插入页脚
            LODOP.ADD_PRINT_HTM('284mm', 0, '207mm', '5mm', tplReplace(this.template.footer, params))
            // 设置刚加入的能让，每页都显示
            LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1)
            // 设置对象在纸张范围内水平居中
            LODOP.SET_PRINT_STYLEA(0, 'Horient', 2)
          }

          // 预览窗口设置
          // LODOP.SET_PREVIEW_WINDOW(0, 0, 1, width + 460, height + 297, '')

          /**
           * 列表部分开始
           */
          let html = '<div style="margin: 0 1px;width: ' + (width - 6.5) + 'mm;padding-bottom: 7mm">'
          if (this.template.thead) {
            html += tplReplace(this.template.thead, params)
          }

          // 表格部分
          if (this.template.lists.item_list.length > 0) {
            html += '<table style="width: 100%;border-spacing: 0;border-top: 1px solid;border-left: 1px solid;text-align: center">'
            let title = ''
            let row = ''
            // 设置表头
            for (let i = 0; i < this.template.lists.item_list.length; i++) {
              const item = this.template.lists.item_list[i]
              const width = item['width'] && item['field'] !== 'image_path' ? 'width: ' + item['width'] + 'mm;' : ''
              const size = item['size'] && item['field'] !== 'image_path' ? 'font-size: ' + item['size'] + 'px' : ''
              const breakAll = item['break'] ? 'word-break: break-all;' : ''
              title += '<th style="border-right: 1px solid;border-bottom: 1px solid;padding: 5px 0;' + width + '">' + item['title'] + '</th>'
              if (item['field'] === 'image_path') {
                const imgWidth = parseInt(item['width']) ? parseInt(item['width']) : 100
                row += '<td style="border-right: 1px solid;border-bottom: 1px solid;padding: 2px;width: ' + imgWidth + 'px;height: ' + imgWidth + 'px">'
                row += '<img src="{$image_path}" style="padding: 0;border: 0;margin: 0" width="' + imgWidth + 'px" height="' + imgWidth + 'px">'
                row += '</td>'
              } else if (item['field'] === 'image_path_sm') {
                row += '<td style="border-right: 1px solid;border-bottom: 1px solid;padding: 2px;width: 50px;height: 50px">'
                row += '<img src="{$image_path}" style="padding: 0;border: 0;margin: 0" width="50px" height="50px">'
                row += '</td>'
              } else {
                row += '<td style="border-right: 1px solid;border-bottom: 1px solid;padding: 5px 0;' + breakAll + width + size + '">{$' + item['field'] + '}</td>'
              }
            }
            if (this.template.lists.fixed_title === 1) {
              html += '<thead><tr>' + title + '</tr></thead>'
            } else {
              html += '<tr>' + title + '</tr>'
            }
            // 设置列表内容
            html += '<tbody>'
            if (this.template.lists && this.template.lists.bar_code_field === 'retainer_list' && this.printData && this.printData['retainer_lists']) {
              // 设置留货人列表内容
              for (let i = 0; i < this.printData['retainer_lists'].length; i++) {
                const item = this.printData['retainer_lists'][i]
                if (item['cover']) {
                  item.image_path = this.completionImage(item['cover'])
                }
                html += '<tr>' + tplReplace(row, item) + '</tr>'
              }
            } else if (this.printData && this.printData['lists']) {
              // 设置列表内容
              for (let i = 0; i < this.printData['lists'].length; i++) {
                const item = this.printData['lists'][i]
                if (item['cover']) {
                  item.image_path = this.completionImage(item['cover'])
                }
                html += '<tr>' + tplReplace(row, item) + '</tr>'
              }
            }
            html += '</tbody></table>'
          }

          /**
           * 模板描述
           * @type {string}
           */
          const desc = localStorage.getItem(this.cacheMark + '-desc')
          if (this.desc) {
            localStorage.setItem(this.cacheMark + '-desc', this.desc)
            params.tpl_desc = this.desc
          } else if (desc) {
            params.tpl_desc = desc
          } else {
            params.tpl_desc = this.template.tpl_desc
          }
          if (this.template.tfoot) {
            html += tplReplace(this.template.tfoot, params)
          }
          html += '</div>'
          // 插入数据表格
          LODOP.ADD_PRINT_HTM(mainTop + 'mm', mainLeft + 'mm', '205mm', '275mm', html)
          // 设置对象在纸张范围内水平居中
          LODOP.SET_PRINT_STYLEA(0, 'Horient', 2)
          // 表格行高粒度 - 自动分页使用
          LODOP.SET_PRINT_STYLEA(0, 'TableRowThickNess', this.template.lists.granularity || 20)

          // 预览窗口
          if (button === 'preview') {
            LODOP.PREVIEW()
          } else {
            LODOP.PRINT()
            // 直接打印
            this.handleCancelModal()
            alert('打印命令已发送')
          }
        }
      } catch (err) {
        console.log('出错了：' + err.toString())
        this.$message.error('检测到你还没有安装打印控件，请下载安装。如已安装，请刷新重试')
      }
    },
    // 获取模板数据
    handleTemplate(tpl_id) {
      if (!this.template || (this.template && this.template.tpl_id !== tpl_id)) {
        this.isLoad = true
        info(tpl_id).then(res => {
          if (res.data) {
            localStorage.setItem(this.cacheMark, res.data.tpl_id)
            this.template = res.data
          }
          this.$nextTick(function() {
            this.isLoad = false
          }.bind(this))
        }).catch(() => {
          this.isLoad = false
        })
      }
    },
    // 处理图片路径
    completionImage(params) {
      return fileUrl(params.path, params.type, 100, 100)
    },
    // 处理图片路径
    completionImageLocal(path) {
      return process.env.VUE_APP_BASE_URL + path
    },
    // 关闭弹出窗口
    handleCancelModal() {
      this.$emit('on-cancel-modal', 'printModal')
    },
    handleDownloadZpi() {
      const a = document.createElement('a')
      a.href = '/CLodop_Setup_for_Win32NT.zip'
      a.click()
    },
    handleOpenUrl() {
      const a = document.createElement('a')
      a.href = 'https://filepcapp.ctaiot.com/dlabel_version/pc/website/%E4%BD%B3%E5%8D%9A%E9%A9%B1%E5%8A%A8%E5%92%8C%E8%BD%AF%E4%BB%B6.rar'
      a.click()
    }
  }
}
</script>
<style lang="scss">
.print {
  .el-dialog__body {
    padding: 0;
  }
}
</style>
<style lang="scss" scoped>
.print .container {
  padding: 0 20px;
  box-sizing: border-box;

  .rule-container {
    display: flex;

    .rule-left {
      width: 70px;
      flex-grow: 0;
      padding-top: 5px;
      font-weight: bold;
    }

    .rule-right {
      flex-grow: 1;
      width: 1%;

      .el-form {
        .el-form-item {
          margin-right: 0;
        }

        .bottom .el-form-item {
          margin-bottom: 5px;
        }
      }
    }
  }

  .tpl-container {
    display: flex;
    flex-wrap: wrap;
    max-height: 327px;
    overflow-y: scroll;
    border: 1px solid #DCDFE6;
    padding: 15px 10px 10px 10px;
  }

  .tpl-item {
    width: 120px;
    height: 155px;
    cursor: pointer;
    padding: 0 10px 10px 10px;

    .image-container {
      overflow: hidden;
      position: relative;

      .avatar {
        width: 100px;
        height: 125px;
      }

      .mark {
        top: -7px;
        right: -17px;
        width: 46px;
        height: 26px;
        display: block;
        text-align: center;
        position: absolute;
        transform: rotate(45deg);
        background-color: #13ce66;
        box-shadow: 0 1px 1px #ccc;

        .el-icon-check {
          color: #ffffff;
          font-size: 12px;
          margin-top: 12px;
          transform: rotate(-45deg);
        }
      }
    }

    .tpl-text {
      width: 100px;
      text-align: center;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
  }
}
</style>
